package org.example.yunshu.demos.service;

import lombok.extern.slf4j.Slf4j;
import org.example.yunshu.demos.constant.Constants;
import org.example.yunshu.demos.mapper.FriendMapper;
import org.example.yunshu.demos.mapper.MessageMapper;
import org.example.yunshu.demos.mapper.SessionMapper;
import org.example.yunshu.demos.model.Friend;
import org.example.yunshu.demos.model.Result;
import org.example.yunshu.demos.model.SessionUser;
import org.example.yunshu.demos.model.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class SessionService {
    @Autowired
    private SessionMapper sessionMapper ;

     @Autowired
     private FriendMapper friendMapper ;

     @Autowired
     private MessageMapper messageMapper ;

    public Object getSessionList(HttpSession httpSession) {
        UserInfo userInfo = (UserInfo) httpSession.getAttribute(Constants.USERINFO_KEY);
        List<SessionUser> list = new ArrayList<>() ;
        //先根据用户id查出当前用户所有的会话id
        List<Integer> sessionList = sessionMapper.getSessionList(userInfo);
        for (Integer sessionId : sessionList){
            SessionUser session = new SessionUser() ;
            session.setSessionId(sessionId);
//          根据会话id,查询最后一条消息
            String lastMessage = messageMapper.getLastMessage(sessionId) ;
            session.setLastMessage(lastMessage);
//             根据会话id查会话中所有的好友
            Friend[] friends = friendMapper.getFriendListBySessionId(sessionId,userInfo.getUserId()) ;
            session.setFriends(friends);
            session.setHeadImage(friends[0].getHeadImage());
            list.add(session);
        }
        return list ;
    }

    public Object createSession(Friend friend, HttpSession httpSession) {
        UserInfo userInfo = (UserInfo) httpSession.getAttribute(Constants.USERINFO_KEY);
        SessionUser sessionUser = new SessionUser() ;
        // session表里添加一个session, 然后获取自增主键
        Integer result =  sessionMapper.addSession(sessionUser) ;
         if(result < 1){
             log.error("添加会话错误");
             return Result.error("添加会话错误");
         }
         Integer result2 = sessionMapper.addSessionUser(
                 sessionUser.getSessionId(), friend.getFriendId(), userInfo.getUserId());
           if(result2 < 1){
               log.error("添加会话用户表错误");
               return Result.error("添加会话用户表错误");
           }

         return sessionUser.getSessionId();
    }
}
